<?php

namespace App\Http\Controllers\Admin;

use App\Models\Scenic;
use App\Models\ScenicWorks;
use App\Validate\ScenicValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 景点打卡
 */
class ScenicController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new Scenic();
        $this->validate = new ScenicValidate();
    }


    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(景点名称)
     * @param type_id int 类型id
     * @param is_play int 是否发布 1是 2否
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 10;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $keywords = request()->keywords;
        $type_id = request()->type_id;
        $is_play = request()->is_play;

        $res = $this->model->lists($keywords, $type_id, $is_play, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->disDataSameLevel($res['data'], 'con_type', ['type_name' => 'type_name']);
        $res['data'] = $this->addSerialNumber($res['data']);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 景点id
     */
    public function detail()
    {
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $id = request()->input('id');
        $scenic = $this->model->detail($id);

        if (!$scenic) {
            return $this->returnApi(201, "参数传递错误");
        }

        $scenic_works_model = new ScenicWorks();
        $scenic->user_num = $scenic_works_model->getTotalUserNumber($id);
        $scenic->works_num = $scenic_works_model->getTotalWorksNumber($id);


        //判断是否可以更改是否需要绑定读者证，有人预约就不允许修改
        $apply_status = $this->model->scenicIsClock($id);
        $scenic->is_can_is_reader = $apply_status ? false : true; //false 有人报名，不允许修改

        $scenic = $scenic->toArray();
        $scenic = $this->disDataSameLevel($scenic, 'con_type', ['type_name' => 'type_name']);
        return $this->returnApi(200, "查询成功", true, $scenic);
    }

    /**
     * 新增
     * @param title string 景点标题
     * @param img string 封面
     * @param intro string 简介
     * @param province string 省
     * @param city string 市
     * @param district string 区
     * @param address string 详细地址
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param start_time string 打卡开始时间
     * @param end_time string 打卡截止时间
     * @param type_id int 类型id
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                throw new  Exception($map);
            }
            $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);
            $this->model->add($this->request->all());

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() ? $e->getMessage() : "新增失败");
        }
    }

    /**
     * 编辑
     * @param id int 景点id
     * @param title string 景点标题
     * @param img string 封面
     * @param intro string 简介
     * @param province string 省
     * @param city string 市
     * @param district string 区
     * @param address string 详细地址
     * @param is_reader int 打卡是否需要绑定读者证   1.是   2.否(默认）
     * @param start_time string 打卡开始时间
     * @param end_time string 打卡截止时间
     * @param type_id int 类型id
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }
        $data = $this->model->detail($this->request->id);
        if ($data['is_play'] == 1) {
            return $this->returnApi(202, "请先撤销才能修改");
        }

        if ($data['is_reader'] != $this->request->is_reader) {
            $scenic_works_model = new ScenicWorks();
            $works_num = $scenic_works_model->where('scenic_id', $this->request->id)->count();
            if ($works_num) {
                return $this->returnApi(202, "已有用户打卡，不能修改打卡是否需要绑定读者证配置");
            }
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                throw new  Exception($map);
            }
            $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);

            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $data = $this->model->detail($this->request->id);
        if ($data['is_play'] == 1) {
            return $this->returnApi(202, "请先撤销才能删除");
        }

        $scenic_works_model = new ScenicWorks();
        $works_num = $scenic_works_model->where('scenic_id', $this->request->id)->count();
        if ($works_num) {
            return $this->returnApi(202, "已有用户打卡，不能删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 撤销 和发布
     * @param id int 景点id
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
